const WebSocket = require('ws');
const http = require('http');

const CONFIG = {
    host: process.env.WS_HOST || '127.0.0.1',
    httpPort: Number(process.env.HTTP_PORT || 3000),
    wsPort: Number(process.env.WS_PORT || 3001),
    testUser: {
        mobile: process.env.TEST_USER_MOBILE || '19900001111',
        password: process.env.TEST_USER_PWD || 'e10adc3949ba59abbe56e057f20f883e',
    },
};

function httpRequest(path, method, body) {
    return new Promise((resolve, reject) => {
        const data = body ? JSON.stringify(body) : '';
        const req = http.request(
            { host: CONFIG.host, port: CONFIG.httpPort, path, method, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } },
            (res) => {
                let buf = '';
                res.on('data', (c) => (buf += c));
                res.on('end', () => {
                    try { resolve(JSON.parse(buf || '{}')); } catch (e) { reject(e); }
                });
            }
        );
        req.on('error', reject);
        if (data) req.write(data);
        req.end();
    });
}

async function login() {
    try {
        await httpRequest('/user-service/user/register', 'POST', { mobile: CONFIG.testUser.mobile, password: CONFIG.testUser.password });
    } catch { }
    const r = await httpRequest('/user-service/user/login', 'POST', { mobile: CONFIG.testUser.mobile, password: CONFIG.testUser.password });
    if (r && r.code === 0 && r.data) return r.data.accessToken;
    throw new Error('登录失败');
}

async function run() {
    console.log('🚀 开始1006抗性聚合测试...');
    const token = await login();

    const ws = new WebSocket(`ws://${CONFIG.host}:${CONFIG.wsPort}/?token=${token}`);
    const send = (obj) => ws.send(JSON.stringify(obj));

    const recv = () => new Promise((resolve) => ws.once('message', (m) => resolve(JSON.parse(m.toString()))));

    await new Promise((resolve) => ws.on('open', resolve));

    // 获取角色列表 3
    send({ c: 3, d: null });
    await recv();

    // 选择角色 5 (默认选第一个)
    send({ c: 5, d: { id: 0 } });
    await recv();

    // 调用1006
    send({ c: 1006, d: null });
    const res = await recv();
    if (res.act_id !== 1006 || res.code !== 0) throw new Error('1006 返回失败');

    const d = res.data || {};
    const keys = ['k_wl', 'k_wei', 'k_feng', 'k_fa', 'k_du', 'k_xi', 'k_luan', 'k_yao', 'k_ll', 'r_bj', 'r_fj', 'r_fz', 'r_hb', 'r_mf', 'r_mz', 'r_zm'];
    const ok = keys.every((k) => typeof d[k] === 'number');
    if (!ok) {
        console.error('❌ 字段不完整: ', d);
        process.exit(1);
    }

    console.log('✅ 1006字段完整性检查通过: ', d);
    ws.close();
    console.log('🎉 1006抗性聚合测试通过');
}

run().catch((e) => {
    console.error('❌ 测试失败:', e.message);
    process.exit(1);
});


